﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.ComponentModel;
using System.Security.Permissions;
using System.Reflection;
using System.Web.UI.Design;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Windows.Forms.Design;
using EnvDTE;
using System.IO;
using System.Windows.Forms;
using System.Data;

namespace Srvtools
{
    [ToolboxItem(true)]
    //[Designer(typeof(LinqWebDataSourceDesigner), typeof(IDesigner))]
    public class LinqWebDataSource : WebDataSource, IGetValues
    {
        
        

        // ---------------------IGetValues----------------------
        public string[] GetValues(string kind)
        {
            if (kind.Equals("RemoteName"))
            {
                string s = EditionDifference.ActiveSolutionName();

                EEPRemoteModule remoteObject = new EEPRemoteModule();
                object[] objs = remoteObject.GetLinqCommandList(new object[] { (object)"", (object)"", (object)"", (object)"", (object)"", (object)"", (object)s });
                if ((null != objs))
                {
                    if (0 == (int)(objs[0]))
                    {
                        string[] sList = (string[])(objs[1]);
                        return sList;
                    }
                    else
                    {
                        return new string[0] { };
                    }
                }
                else
                    return new string[0] { };
            }
            else
                return new string[0] { };
        }
        // -----------------------------------------------------
    }

    //public enum ExecuteMode
    //{
    //    ExecuteQuery = 1,

    //    ExecuteSQL = 2
    //}

    //public class LinqWebDataSourceView : DataSourceView
    //{
    //    private IDataSource _owner;
    //    private string _viewName;

    //    public IDataSource Owner
    //    {
    //        get
    //        {
    //            return _owner;
    //        }
    //        set
    //        {
    //            _owner = value;
    //        }
    //    }

    //    public string ViewName
    //    {
    //        get
    //        {
    //            return _viewName;
    //        }
    //        set
    //        {
    //            _viewName = value;
    //        }
    //    }

    //    public LinqWebDataSourceView(IDataSource owner, string viewName)
    //        : base(owner, viewName)
    //    {
    //        _owner = owner;
    //        _viewName = viewName;
    //    }

    //    protected override IEnumerable ExecuteSelect(DataSourceSelectArguments arguments)
    //    {
    //        LinqWebDataSource linqWebDataSource = (LinqWebDataSource)_owner;

    //        string moduleName = linqWebDataSource.GetModuleName();
    //        string linqCommandName = linqWebDataSource.GetLinqCommandName();
    //        Type resultType = linqWebDataSource.GetResultType();

    //        if (string.IsNullOrEmpty(moduleName) || string.IsNullOrEmpty(linqCommandName) || resultType == null)
    //        {
    //            return null;
    //        }

    //        DataSet dataSet = null;
    //        if (linqWebDataSource.ExecuteMode == ExecuteMode.ExecuteQuery)
    //        {
    //            int skip = linqWebDataSource.Skip;
    //            int take = linqWebDataSource.Take;
    //            string where = linqWebDataSource.Where;
    //            string orderBy = linqWebDataSource.OrderBy;
    //            //string groupByKey = linqWebDataSource.GroupByKey;
    //            //string groupByElement = linqWebDataSource.GroupByElement;

    //            dataSet =CliUtils.LinqExecuteQuery(moduleName, linqCommandName, resultType, skip, take, where, orderBy, string.Empty, string.Empty, string.Empty);
                
    //        }
    //        else
    //        {
    //            string sql = linqWebDataSource.SQL;
    //            if (string.IsNullOrEmpty(sql))
    //            {
    //                return null;
    //            }

    //            dataSet = CliUtils.LinqExecuteSQL(moduleName, linqCommandName, resultType, sql);
    //        }

    //        if (dataSet != null)
    //        {
    //            return dataSet.Tables[0].DefaultView;
    //        }
    //        else
    //        {
    //            return null;
    //        }
    //    }

    //    protected override int ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues)
    //    {
    //        LinqWebDataSource linqWebDataSource = (LinqWebDataSource)_owner;

    //        string moduleName = linqWebDataSource.GetModuleName();
    //        string linqCommandName = linqWebDataSource.GetLinqCommandName();

    //        Type type = linqWebDataSource.GetResultType();

    //        object entity = Activator.CreateInstance(type);
    //        object oldEntity = Activator.CreateInstance(type);

    //        IEnumerator names = values.Keys.GetEnumerator();
    //        IEnumerator values1 = values.Values.GetEnumerator();
    //        IEnumerator values2 = oldValues.Values.GetEnumerator();

    //        while (names.MoveNext())
    //        {
    //            string name = names.Current.ToString();

    //            PropertyInfo property = type.GetProperty(name);
    //            Type propertyType = property.PropertyType;

    //            object value = (values1.MoveNext()) ? values1.Current : null;
    //            object oldValue = (values2.MoveNext()) ? values2.Current : null;

    //            if (value != null && value.GetType() != propertyType)
    //            {
    //                if (propertyType.Name == "Nullable`1")
    //                {
    //                    Type valueType = propertyType.GetGenericArguments()[0];
    //                    value = Convert.ChangeType(value, valueType);
    //                }
    //                else
    //                {
    //                    value = Convert.ChangeType(value, propertyType);
    //                }
    //            }
    //            if (oldValue != null && oldValue.GetType() != propertyType)
    //            {
    //                if (propertyType.Name == "Nullable`1")
    //                {
    //                    Type valueType = propertyType.GetGenericArguments()[0];
    //                    oldValue = Convert.ChangeType(oldValue, valueType);
    //                }
    //                else
    //                {
    //                    oldValue = Convert.ChangeType(oldValue, propertyType);
    //                }
    //            }

    //            property.SetValue(entity, value, new object[] { });
    //            property.SetValue(oldEntity, oldValue, new object[] { });
    //        }

    //        CliUtils.LinqUpdate(moduleName, linqCommandName, new object[] { new object[] { entity, oldEntity } });

    //        return 1;
    //    }

    //    protected override int ExecuteInsert(IDictionary values)
    //    {
    //        LinqWebDataSource linqWebDataSource = (LinqWebDataSource)_owner;

    //        string moduleName = linqWebDataSource.GetModuleName();
    //        string linqCommandName = linqWebDataSource.GetLinqCommandName();

    //        Type type = linqWebDataSource.GetResultType();

    //        object entity = Activator.CreateInstance(type);

    //        IEnumerator names = values.Keys.GetEnumerator();
    //        IEnumerator values1 = values.Values.GetEnumerator();
    //        while (names.MoveNext())
    //        {
    //            string name = names.Current.ToString();

    //            PropertyInfo property = type.GetProperty(name);
    //            Type propertyType = property.PropertyType;

    //            object value = (values1.MoveNext()) ? values1.Current : null;
    //            if (value != null && value.GetType() != propertyType)
    //            {
    //                if (propertyType.Name == "Nullable`1")
    //                {
    //                    Type valueType = propertyType.GetGenericArguments()[0];
    //                    value = Convert.ChangeType(value, valueType);
    //                }
    //                else
    //                {
    //                    value = Convert.ChangeType(value, propertyType);
    //                }
    //            }

    //            property.SetValue(entity, value, new object[] { });
    //        }

    //        CliUtils.LinqInsert(moduleName, linqCommandName, new object[] { entity });

    //        return 1;
    //    }

    //    protected override int ExecuteDelete(IDictionary keys, IDictionary oldValues)
    //    {
    //        LinqWebDataSource linqWebDataSource = (LinqWebDataSource)_owner;

    //        string moduleName = linqWebDataSource.GetModuleName();
    //        string linqCommandName = linqWebDataSource.GetLinqCommandName();

    //        Type type = linqWebDataSource.GetResultType();

    //        object entity = Activator.CreateInstance(type);

    //        IEnumerator names = oldValues.Keys.GetEnumerator();
    //        IEnumerator values = oldValues.Values.GetEnumerator();
    //        while (names.MoveNext())
    //        {
    //            string name = names.Current.ToString();

    //            PropertyInfo property = type.GetProperty(name);
    //            Type propertyType = property.PropertyType;

    //            object value = (values.MoveNext()) ? values.Current : null;
    //            if (value != null && value.GetType() != propertyType)
    //            {
    //                if (propertyType.Name == "Nullable`1")
    //                {
    //                    Type valueType = propertyType.GetGenericArguments()[0];
    //                    value = Convert.ChangeType(value, valueType);
    //                }
    //                else
    //                {
    //                    value = Convert.ChangeType(value, propertyType);
    //                }
    //            }

    //            property.SetValue(entity, value, new object[] { });
    //        }

    //        CliUtils.LinqDelete(moduleName, linqCommandName, new object[] { entity });

    //        return 1;
    //    }
    //}

    //public class LinqWebDataSourceDesigner : DataSourceDesigner
    //{
    //    private DesignerActionListCollection _actionLists;
    //    private bool _isRefresh = false;

    //    // 只有get，没有set。
    //    public override DesignerActionListCollection ActionLists
    //    {
    //        get
    //        {
    //            if (null == _actionLists)
    //            {
    //                _actionLists = new DesignerActionListCollection();
    //                _actionLists.Add(
    //                    new LinqWebDataSourceActionList(this.Component, this));
    //            }
    //            return _actionLists;
    //        }
    //    }

    //    public override DesignerDataSourceView GetView(string viewName)
    //    {
    //        if (_isRefresh)
    //        {
    //            //return new DesignerLinqWebDataSourceView(this, viewName);
    //            return null;
    //        }
    //        else
    //        {
    //            return base.GetView(viewName);
    //        }
    //    }

    //    public override void RefreshSchema(bool preferSilent)
    //    {
    //        _isRefresh = true;
    //        this.OnSchemaRefreshed(EventArgs.Empty);
    //    }

    //    public override bool CanRefreshSchema
    //    {
    //        get
    //        {
    //            return true;
    //        }
    //    }

    //    public override bool CanConfigure
    //    {
    //        get
    //        {
    //            return true;
    //        }
    //    }
    //}

    //public class LinqWebDataSourceActionList : DesignerActionList
    //{
    //    private LinqWebDataSource _linqWebDataSource;
    //    private LinqWebDataSourceDesigner _designer;

    //    public LinqWebDataSourceActionList(IComponent component, DataSourceDesigner designer)
    //        : base(component)
    //    {
    //        this._linqWebDataSource = component as LinqWebDataSource;
    //        this._designer = designer as LinqWebDataSourceDesigner;
    //    }


    //    public void RefreshSchema()
    //    {
    //        _designer.RefreshSchema(false);
    //    }

    //    public override DesignerActionItemCollection GetSortedActionItems()
    //    {
    //        DesignerActionItemCollection items = new DesignerActionItemCollection();

    //        items.Add(new DesignerActionMethodItem(this, "RefreshSchema", "Refresh Schema...", "Action", true));

    //        return items;
    //    }
    //}

    ////public class DesignerLinqWebDataSourceView : DesignerDataSourceView
    ////{
    ////    private object _owner;
    ////    private string _viewName;

    ////    public DesignerLinqWebDataSourceView(LinqWebDataSourceDesigner owner, string viewName)
    ////        : base(owner, viewName)
    ////    {
    ////        _owner = owner;
    ////        _viewName = viewName;
    ////    }

    ////    public override IDataSourceViewSchema Schema
    ////    {
    ////        get { return new LinqColumnsSchema(_owner, _viewName); }
    ////    }
    ////}

    //public class ResultTypeNameEditor : UITypeEditor
    //{
    //    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    //    public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
    //    {
    //        return UITypeEditorEditStyle.DropDown;
    //    }

    //    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    //    public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, System.IServiceProvider provider, object value)
    //    {
    //        IWindowsFormsEditorService service = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
    //        Projects projects = EditionDifference.ActiveSolution().Projects;

    //        List<string> list = new List<string>();
    //        foreach (Project project in projects)
    //        {
    //            try
    //            {
    //                Configuration config = project.ConfigurationManager.ActiveConfiguration;
    //                DirectoryInfo dictInfo = (new DirectoryInfo(project.FullName)).Parent;

    //                string fileName = string.Empty;

    //                foreach (Property prop in config.Properties)
    //                {
    //                    if (prop.Name == "OutputPath")      // OutputFileName
    //                    {
    //                        fileName += prop.Value.ToString();
    //                    }
    //                }

    //                foreach (Property prop in project.Properties)
    //                {
    //                    if (prop.Name == "OutputFileName")      // OutputFileName
    //                    {
    //                        fileName += prop.Value.ToString();
    //                    }
    //                }

    //                string[] ss = fileName.Split(@"\".ToCharArray());
    //                foreach (string s in ss)
    //                {
    //                    if (s == "..") dictInfo = dictInfo.Parent;
    //                }

    //                fileName = dictInfo.FullName + @"\" + fileName.Replace("..", "");

    //                if (!File.Exists(fileName))
    //                {
    //                    continue;
    //                }

    //                Assembly assembly = Assembly.LoadFile(fileName);
    //                Type[] types = assembly.GetTypes();
    //                foreach (Type type in types)
    //                {
    //                    if (type.GetInterface("INotifyPropertyChanging") != null)
    //                    {
    //                        list.Add(type.FullName);
    //                    }
    //                }
    //            }
    //            catch
    //            {
    //            }
    //        }

    //        if (service != null)
    //        {
    //            StringListSelector slector = new StringListSelector(service, list.ToArray());
    //            string strValue = (string)value;
    //            if (slector.Execute(ref strValue)) value = strValue;
    //        }

    //        return value;
    //    }
    //}
}
